const variables = this.getVariables();
const proxy = variables.find(item => item.name === 'environmentType')?.value || '';
const stream_url = variables.find(x => x.name == "stream_url").value || '';
const videoPlatform = variables.find(x => x.name == "videoPlatform")?.value;
const _this = this;

// 公共请求方法
function baseRequest(url, body, method) {
    const headers = { "Content-Type": "application/json" };
    const option = { method, headers, body: JSON.stringify(body) };
    return fetch(url, option).then(res => res.json());
}

// 设置当前融合视频数量
function setFuseNum(num) {
    const $numTitle = _this.getApiWidgetByAliasName('fuse_num_title').widgetObj;
    $numTitle._option.links.text = `选择视频融合点 (${num}/10)`;
    $numTitle.render();
}

// 处理融合视频列表
async function renderFuseList() {
    const url = `/${proxy}SummaryAssessmentSV/videoFuse/list`;
    const { name = '' } = window._videoFuse.fuseListSearch || {};
    const loading = layer.load(0);
    const res = await baseRequest(url, { fuseName: name }, 'POST');
    layer.close(loading);
    const dataSource = (res.result || []).map(item => {
        const children = (item.videoFuseDetails).map(i => {
            const equipmentInfo = i.equipmentInfo ? JSON.parse(i.equipmentInfo) : {};
            return { ...equipmentInfo, title: i.equipmentName };
        })
        return { ...item, title: item.fuseName, children };
    });
    const $inspection = _this.getApiWidgetByAliasName('inspection_list').widgetObj;
    $inspection._option.dataSource = [{ id: "root", title: "我的分组", children: dataSource }];
    $inspection.render();

    const data = window._videoFuse.fuseListSelect;
    if (data?.id && data?.fuseName) {
        const item = dataSource.find(i => i.id === data?.id);
        if (item) _videoFuse.fuseListSelect = item;
        const node = $($inspection.container).find(`#${data.id}`);
        node.addClass('tree_node_active');
    } else {
        _videoFuse.fuseListSelect = undefined;
    }
}

// 设备数据处理
function handleEquipmentData(data) {
    const { id, equipmentName, equipmentCode, equipmentId, equipmentConfig } = data || {};
    const gbVideoConfig = equipmentConfig?.gbVideoConfig || {};
    let channelId = gbVideoConfig?.videoChannelId;
    let deviceId = gbVideoConfig?.sipUser;
    let stream_path;
    if (channelId && deviceId) stream_path = `${deviceId}/${channelId}`;

    return {
        title: equipmentName,
        id,
        stream_path,
        channelId,
        deviceId,
        equipmentName,
        equipmentCode,
        equipmentId: equipmentId || equipmentCode,
        protocol: videoPlatform === 'security' ? "hls,rtsp" : undefined,
    }
}

// 查询视频融合监控点
const getVideoFusionPoint = async function () {
    const loading = layer.load(0);
    const table = _this.getApiWidgetByAliasName('fuse_modal_table').widgetObj;
    const { id = '', name = '' } = window._videoFuse.videoAreaSearch || {};
    const url = `/${proxy}Basics/basics-main/system/equipmentObject/listDetailByEquipmentCode`;
    const res = await baseRequest(`${url}?equipmentTypeCode=camera&areaId=${id}&equipmentName=${name}`);
    // const url = `/${proxy}Basics/basics-main/system/equipmentObject/listDetailByEquipmentCodes`;
    // const body = { equipmentTypeCodes: ['camera'], areaId: id, equipmentName: name };
    // const res = await baseRequest(url, body, 'POST');
    layer.close(loading);
    const rows = (res?.result?.rows || []).map(item => {
        const config = item?.equipmentConfig?.gbVideoConfig || {};
        return { ...item, LAY_DISABLED: !config?.sipUser || !config?.videoChannelId };
    })
    table.tbodyData = rows;
    table.render();
}

// 查询视频融合流地址
async function getFuse(data = [], streamId) {
    layer.msg('视频融合中, 预计需要60s');
    const loading = layer.load(0);
    const urls = videoPlatform === 'security' ? data.map(item => item?.urls?.rtsp) : data.map(item => item.stream_path);
    const body = videoPlatform === 'security'
        ? { "urls": urls, stream_path: streamId }
        : { "local_stream_paths": urls, stream_path: streamId };
    const res = await baseRequest(`/StreamUrl/api/v1/stream/stitch`, body, 'POST');
    layer.close(loading);
    if (res?.state) return res.data;
    layer.msg(res?.desc || '视频融合失败');
    return false;
}

// 摄像头归位
async function handleVideoHoming(videoFuseId) {
    layer.msg('摄像头归位中, 预计需要10s');
    const url = `/${proxy}SummaryAssessmentSV/videoFuse/batchResumePTZPosition`;
    await baseRequest(url, { videoFuseId }, 'POST');
}

// 处理右侧视频
async function renderSullivan() {
    if (!_videoFuse.fuseListSelect) return;
    const { id, children = [], fuseName } = _videoFuse.fuseListSelect;
    const $video = _this.getApiWidgetByAliasName('fuse_video').widgetObj;
    const $videoSwiper = _this.getApiWidgetByAliasName('fuse_video_swiper').widgetObj;
    $video.sullivan.closeAll();
    $videoSwiper.sullivan.closeAll();
    await $videoSwiper.sullivan.addPlayers(children);
    const data = $videoSwiper.sullivan.getData();
    const loading = layer.load(0);
    await handleVideoHoming(id);
    await new Promise((resolve) => {
        setTimeout(() => { resolve() }, 6000);
    })
    layer.close(loading);
    const res = await getFuse(data, id);
    if (!res) return;
    $video.sullivan.addPlayer({
        ...res,
        playerType: 'webrtc',
        equipmentName: fuseName || '融合预览',
    });
}

// 区域数据处理
function handleAreaData(data) {
    if (!data || !data.length) return [];
    return data.map((item) => ({
        ...item,
        type: 'area',
        title: `${item.projectAreaName}(${item.count})`,
        children: handleAreaData(item?.projectLocationAreas || []),
    }));
}

// 区域树
async function handleAreaTree() {
    const url = `/${proxy}Basics/basics-main/system/projectArea/projectAreaEquCount`;
    const loading = layer.load(0);
    const res = await baseRequest(`${url}?typeCode=camera`);
    console.log(res, 'res')
    layer.close(loading);
    const dataSource = (res?.result || []).map(item => ({
        id: item.id,
        type: 'project',
        title: `${item.projectName}(${item.count})`,
        children: handleAreaData(item.projectLocationAreas),
    }));
    console.log(dataSource, 'dataSourcedataSource')
    const areaTree = _this.getApiWidgetByAliasName('area_tree').widgetObj;
    areaTree._option.dataSource = dataSource;
    areaTree.render();
}


window._videoFuse = {
    proxy,
    stream_url,
    videoPlatform,
    fuseListSearch: {}, // 视频融合列表搜索项
    fuseListSelect: undefined, // 视频融合列表选中项
    oldFuseSelect: undefined, // 视频融合列表选中项 - 缓存
    videoAreaSearch: {}, // 视频融合点搜索项
    baseRequest,
    setFuseNum,
    renderFuseList,
    getVideoFusionPoint,
    getFuse,
    renderSullivan,
    handleEquipmentData,
    canSave: false, // 融合视频是否可保存
    handleAreaTree,
}